package com.zenika.zentracker.hibernate.sql;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.hibernate.Interceptor;

import com.zenika.zentracker.hibernate.jdbc.SQLSniffer;

/**
 * Proxy used by the ZenTracker tool to monitor the execution time of a <tt>CallableStatement</tt>.
 * 
 * Only the methods executing the query are redefined from the <tt>DefaultCallableStatementProxy</tt>
 * 
 * @see DefaultCallableStatementProxy
 * @author Zenika
 * 
 */
public class ZenTrackerCallableStatementProxy extends DefaultCallableStatementProxy {

    /**
     * @param targetCS The real CallableStatement object
     * @param interceptor A Hibernate Interceptor
     * @param sql The SQL query String
     */
    public ZenTrackerCallableStatementProxy(CallableStatement targetCS, Interceptor interceptor, String sql) {
        super(targetCS, interceptor, sql);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.zenika.zentracker.hibernate.sql.DefaultPreparedStatementProxy#executeQuery()
     */
    public ResultSet executeQuery() throws SQLException {
        long start = System.currentTimeMillis();
        ResultSet rs = super.executeQuery();
        logQueryExecutionTime(System.currentTimeMillis() - start);
        return rs;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.zenika.zentracker.hibernate.sql.DefaultPreparedStatementProxy#executeBatch()
     */
    public int[] executeBatch() throws SQLException {
        long start = System.currentTimeMillis();
        int[] result = super.executeBatch();
        logQueryExecutionTime(System.currentTimeMillis() - start);
        return result;
    }

    /**
     * @param executionTime
     */
    private void logQueryExecutionTime(long executionTime) {
        if (interceptor != null) {
            SQLSniffer.getInstance().addSQLExecution(interceptor, query, executionTime);
        }
    }

}
